package com.carworld.model;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.carworld.model.base.BaseCard;
import com.carworld.utils.DateUtils;
import com.carworld.utils.DicUtil;
import com.carworld.utils.weixin.TemplateMessage;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Card extends BaseCard<Card> {
	public static final Card dao = new Card().dao();



	//用户id查会员卡
	public Card findCardByUserId(String userId){
		String sql="select *  from card t where t.user_id=?";
		return  this.findFirst(sql,userId);
	}

	//消费者id查shareholder
	public String  findCardShareholderByUserId(String userId){
		String sql="select t.user_of_shareholder  from card t where t.user_id=?";
		return  Db.queryStr(sql,userId);
	}

	//我的套餐数
	public String countCardComboById(String userId){
		String sql="select count(*) as countNum  from card t where t.user_of_shareholder=?";
		return Db.queryStr(sql,userId);
	}
	//返回人脉列表
	public List<Card> findCardCombo(String userId) {
		String sql="select user_photo,s.name  from card t left join sys_user s on t.user_id=s.id where t.user_of_shareholder=?";
		return Db.query(sql,userId);
	}

	//人脉总数

	public String countCardTeamById(String userId){
		String sql="select count(*) as countNum  from card t where t.share_by=?";//这里应该用uset-of-shareholder 不是share_by
		return Db.queryStr(sql,userId);
	}

	//返回人脉列表
	public List<Card> findCardTeam(String userId,int index) {//e04f9f0468f441e39fcb799034286900
		String sql="select ss.user_photo,ss.user_nickname,DATE_FORMAT(t.create_time,'%Y,%m,%d'),IFNULL(SUM(t2.order_dividend),0.00) " +
				"from card t left join divident_daily_statistics t2 on t.user_id= t2.order_user left join sys_user ss on t.user_id=ss.id " +
				" where t.share_by = ? " + //这里应该用uset-of-shareholder 不是share_by
				"group by t.user_id limit ?,15";
		return Db.query(sql,userId,index);
	}

	/**
	 * 查询用户绑定的会员卡信息
	 * 
	 * @param userId
	 * @return
	 */
	public Card findCardByIdInCache(String userId) {
		String sql = " select groupid, cardid, cardname, amt, create_time, cardcode, create_time,share_by, remaining_num, sharing_num, user_id, user_of_shareholder from card c where c.user_id= ?  ";
		return this.findFirstByCache(DicUtil.CACHE_CARD, userId + "cardInfo", sql, userId);
	}
	
	
	/**
	 * 时时查询用户绑定的会员卡信息
	 * 
	 * @param userId
	 * @return
	 */
	public Card findCardById(String userId) {
		String sql = " select groupid, cardid, cardname, amt, create_time, cardcode, create_time,share_by, remaining_num, sharing_num, user_id, user_of_shareholder from card c where c.user_id= ?  ";
		return this.findFirst(sql, userId);
	}
	/**
	 *
	 * 查看可分享的套餐
	 *
	 * @param userId
	 * @return
	 */
	public Page<Record> myCardMeals2(String userId) {
		List<String> whereParams = new ArrayList<String>();
		String select = "SELECT m.meal_id,m.meal_name,m.meal_price,c.cardid,c.user_id,c.share_by,c.user_of_shareholder,m.meal_endtime,csm.card_meal_sharenumber";
		StringBuffer sBuffer = new StringBuffer(
				" FROM meal m LEFT JOIN card_set_meal csm ON m.meal_id = csm.card_set_meal_id LEFT JOIN card c ON csm.card_id = c.cardid ");
		sBuffer.append(" WHERE c.user_id=? ");
		whereParams.add(userId);
		sBuffer.append(" AND m.meal_endtime>NOW()");
		sBuffer.append(" And csm.card_meal_sharenumber >0 ");
		sBuffer.append(" ORDER BY meal_updatetime DESC ");
		System.out.println("whereParams"+whereParams.toArray());
		//暂弃用从缓存中读取会员卡的方案
		/*return Db.paginateByCache(DicUtil.CACHE_CARD, userId + type, 1, 10, select, sBuffer.toString(),
				whereParams.toArray());*/
		return Db.paginate(1, 10, select, sBuffer.toString(),whereParams.toArray());
	}


	/**
	 * 
	 * 查看可供使用的套餐以及已过期的套餐
	 * 
	 * @param userId
	 * @return
	 */
	public Page<Record> myCardMeals(String userId, String type) {
		List<String> whereParams = new ArrayList<String>();
		String select = " SELECT csm.card_meal_number,m.meal_id,m.meal_name,m.meal_price,c.cardid,c.user_id,c.share_by,c.user_of_shareholder,csm.card_meal_endtime";
		StringBuffer sBuffer = new StringBuffer(
				" FROM meal m LEFT JOIN card_set_meal csm ON m.meal_id = csm.card_set_meal_id LEFT JOIN card c ON csm.card_id = c.cardid ");
		sBuffer.append(" WHERE c.user_id=? ");
		whereParams.add(userId);
		if ("0".equals(type)) {
			sBuffer.append(" AND  csm.card_meal_endtime>NOW()");
		} else if ("1".equals(type)) {
			sBuffer.append("And csm.card_meal_endtime<NOW()");
		}
		sBuffer.append(" And csm.card_meal_number >0 ");
		sBuffer.append(" ORDER BY meal_updatetime DESC ");
		System.out.println("whereParams"+whereParams.toArray());
		//暂弃用从缓存中读取会员卡的方案
		/*return Db.paginateByCache(DicUtil.CACHE_CARD, userId + type, 1, 10, select, sBuffer.toString(),
				whereParams.toArray());*/
		return Db.paginate(1, 10, select, sBuffer.toString(),whereParams.toArray());
	}

	/**
	 * 查看分享的套餐个数
	 */
	public int vipCardCount(String userId) {
		String sql = "select IFNULL(count(card_set_meal_id),0) as meal_count  from card_set_meal cms left join card c "
				+ "on c.cardid=cms.card_id where c.share_by= ? and c.user_id <> c.user_of_shareholder";
		int cardNum = Db.queryInt(sql, userId);
		return cardNum;
	}

	/**
	 * 查看可用的套餐数量
	 */
	public int findMealNum(String userId) {
		String sql = "select IFNULL(count(csm.card_set_meal_id),0) as mealNum from card_set_meal csm left join card c on c.cardid = csm.card_id where c.user_id= ? and csm.card_meal_number >0";
		int mealNum = Db.queryInt(sql, userId);
		return mealNum;
	}

	
	/**
	 * 查询股东/会员 已分享套餐信息 (暂未显示分享的套餐名称)
	 * 

	 *            0为会员分享，1为股东分享
	 * @return
	 */
	public Page<Record> vipCardSharedInfo(String userId, String userRole) {
		List<String> whereParams = new ArrayList<String>();
		String sql = "SELECT c.create_time, su.name,su.user_photo ";
		StringBuffer sBuffer = new StringBuffer("FROM card c left join sys_user su on su.id=c.user_id");
		sBuffer.append(" WHERE 1=1 ");
		if ("0".equals(userRole)) {
			this.addEqualCondition(sBuffer, whereParams, "c.share_by", userId);
		} else if ("1".equals(userRole)) {
			this.addEqualCondition(sBuffer, whereParams, "c.user_of_shareholder", userId);
		}
		sBuffer.append(" and  c.user_id <> c.user_of_shareholder");
		return Db.paginateByCache(DicUtil.CACHE_CARD, userId + "shared" + userRole, 1, 100, sql, sBuffer.toString(),
				whereParams.toArray());
	}
	
	/**
	 * 查看自己的人脉会员
	 * @param userId
	 * @param source 1:一级分红人脉，2：二级分红人脉
	 * @return
	 */
	public Page<Record> getMyConnection(String userId,String source) {
		List<String> whereParams = new ArrayList<String>();
		String sql = "SELECT c.create_time, su.name,su.user_photo ";
		StringBuffer sBuffer = new StringBuffer("FROM card c left join sys_user su on su.id=c.user_id");
		sBuffer.append(" WHERE 1=1 ");
		if ("1".equals(source)) {
			this.addEqualCondition(sBuffer, whereParams, "c.share_by", userId);
		} else if ("2".equals(source)) {
			sBuffer.append(" and c.share_by <> c.user_of_shareholder");
		}
		sBuffer.append(" and  c.user_id <> c.user_of_shareholder");
		return Db.paginateByCache(DicUtil.CACHE_CARD, userId + "shared" + source, 1, 100, sql, sBuffer.toString(),
				whereParams.toArray());
	}
	

	/**
	 * 用户领取会员卡套餐保存会员卡、套餐信息
	 * 
	 * @param shareBy
	 * @param mealId
	 * @param userId
	 * @return
	 */
	public JSONObject saveCardAndMeal(String shareholderId, String shareBy, long mealId, String userId) {
		JSONObject jsonObject = new JSONObject();

		// 获取对应股东的会员卡信息
		Card cardOfShareholder = Card.dao.findCardByIdInCache(shareholderId);

		//获取对应股东的分享套餐的信息
		CardSetMeal taocanShareholder=CardSetMeal.dao.findMealOfCard2(mealId,cardOfShareholder.getCardid());

		// 获取对应股东的用户信息
		SysUser shareholderInfo = SysUser.dao.findByIdInCache(shareholderId);

		// 获取分享股东所属门店的信息
		SysOffice officeInfo = SysOffice.dao.findShopInCache(shareholderInfo.getCompanyId());

		// 获取分享者的用户信息
		SysUser sharerInfo = SysUser.dao.findByIdInCache(shareBy);

		// 获取领卡人的用户信息
		SysUser receivedCardUser = SysUser.dao.findByIdInCache(userId);

		if (receivedCardUser != null && receivedCardUser.getCompanyId() == null) {
			receivedCardUser.setCompanyId(officeInfo.getId()); // 设置用户所属门店
			receivedCardUser.setUserOfShareholder(shareBy); // 绑定股东和会员,每个会员只能绑定一个股东
		}

		if (receivedCardUser.getUserRole() == null) {
			receivedCardUser.setUserRole("0"); // 默认为会员
		}
		receivedCardUser.update(); // 更新领卡人的会员信息

		if (taocanShareholder != null && taocanShareholder.getCardMealSharenumber() < 1) {
			jsonObject.put("state", "-1");
			jsonObject.put("message", "sorry!分享的套餐已被抢光了，下次要早点来哦~");
		} else {
			// 先查询领卡套餐的人是否有会员卡
			Card CardOfReceiver = Card.dao.findCardByIdInCache(userId);
			Date date = new Date();

			if (null == CardOfReceiver) {
				System.out.println("该会员还没卡，默认添加一张普通会员卡");
				Card card = new Card();
				long cardId = date.getTime();
				card.setGroupid(shareholderInfo.getCompanyId());
				card.setCardid(cardId);
				card.setCardname("【"+receivedCardUser.getName()+receivedCardUser.getMobile()+"】茉德会员卡");
				card.setCardcode(receivedCardUser.getMobile());
				card.setAmt(new BigDecimal(0.00));
				card.setAvaiabletime(365);
				card.setIsshared("是");
				card.setSource("门店");
				card.setStatus("使用");
				card.setComment("来源于领取会员[" + shareholderInfo.getName() + "]分享套餐");
				card.setCreateTime(date);
				card.setUserId(userId);
				card.setUserOfShareholder(shareholderId);
				card.setShareBy(shareBy);
				card.setRemainingNum(1);
				card.setSharingNum(0); 
				card.save();

				// 加入缓存中
				// CacheKit.put(DicUtil.CACHE_CARD, userId, card);
				jsonObject.put("message", "会员卡套餐已经收入囊中，快去查看吧~");
				// 开始绑定套餐
				Meal mm= Meal.dao.findMealById(mealId);
				if (null == mm) {
					jsonObject.put("state", "-1");
					jsonObject.put("message", "此套餐分享活动已结束~");
					System.out.println("此套餐分享活动已结束");
				}else {
					CardSetMeal setMeal = new CardSetMeal();
					setMeal.setCardId(cardId);
					setMeal.setCardMealId(date.getTime()); // 以时间戳作为主键id
					setMeal.setCardSetMealId(mealId);
					Date now = new Date();
					Integer da=new Integer(mm.getMealValidity());
					Date endDate = org.apache.commons.lang3.time.DateUtils.addDays(now, da);
					setMeal.setCardMealEndtime(endDate);
					setMeal.setCardMealStarttime(now);
					setMeal.setCardMealNumber(1);
					setMeal.save();
					// 加入缓存中
					CacheKit.put(DicUtil.CACHE_MEAL, mealId + cardId, setMeal);

					// 修改分享者分享的会员卡
					taocanShareholder.setCardMealSharenumber(taocanShareholder.getCardMealSharenumber()-1);
					taocanShareholder.update();
				}
			} else {
				long exitedCardId = CardOfReceiver.getCardid();
				// 再查询有没有套餐
				CardSetMeal cardSetMeal = CardSetMeal.dao.findMealOfCard(mealId, exitedCardId);
				if (null != cardSetMeal) {
					jsonObject.put("state", "-1");
					jsonObject.put("message", "您已经领过此套餐，不必重复领取~");
					System.out.println("该会员已有此套餐");
				} else {
					System.out.println("该会员已有卡，但无套餐，只绑定套餐");
					Meal mm = Meal.dao.findMealById(mealId);
					if (null == mm) {
						jsonObject.put("state", "-1");
						jsonObject.put("message", "此套餐分享活动已结束~");
						System.out.println("此套餐分享活动已结束");
					} else {
						Date now = new Date();
						Integer da=new Integer(mm.getMealValidity());
						Date endDate = org.apache.commons.lang3.time.DateUtils.addDays(now, da);
						CardSetMeal setMeal = new CardSetMeal();
						setMeal.setCardId(exitedCardId);
						setMeal.setCardMealId(date.getTime());
						setMeal.setCardSetMealId(mealId);
						setMeal.setCardMealEndtime(endDate);
						setMeal.setCardMealNumber(1);
						setMeal.setCardMealStarttime(now);
						setMeal.save();
						// 加入缓存中
						// CacheKit.put(DicUtil.CACHE_CARD, exitedCardId, setMeal);
						jsonObject.put("message", "会员套餐已收入囊中~");
						// 修改分享者分享的会员卡
						taocanShareholder.setCardMealSharenumber(taocanShareholder.getCardMealSharenumber() - 1);
						taocanShareholder.update();
					}
				}

			}

		}

		jsonObject.put("officeAddress", officeInfo.getAddress());
		jsonObject.put("officeName", officeInfo.getName());
		jsonObject.put("sharerName", sharerInfo.getName());
		jsonObject.put("sharerPhoto", sharerInfo.getUserPhoto());
		jsonObject.put("userIsFocus", receivedCardUser.getUserIsfocus());

		return jsonObject;
	}

	

	/**
	 * 首次关注公众号，领取优惠券
	 *
	 * @param mealId
	 * @param userId
	 * @return
	 */
	public JSONObject saveCouponByFocus(long mealId, String userId) {
		JSONObject jsonObject = new JSONObject();
		
		// 获取领卡人的用户信息
		SysUser receivedCouponUser = SysUser.dao.findByIdInCache(userId);
		if (receivedCouponUser != null && receivedCouponUser.getCompanyId() == null) {
			receivedCouponUser.setCompanyId("a6134faf9a844fe0ae006c7bd1d9a6d5"); //临时先绑定到茉德精品火锅门店
		}
		if (receivedCouponUser.getUserRole() == null) {
			receivedCouponUser.setUserRole("0"); // 默认为会员
		}
		receivedCouponUser.update(); // 更新领卡人的会员信息
			// 先查询领卡套餐的人是否有会员卡
			Card CardOfReceiver = Card.dao.findCardByIdInCache(userId);
			Date date = new Date();

			if (null == CardOfReceiver) {
				System.out.println("该用户还没卡，默认添加一张普通会员卡");
				Card card = new Card();
				long cardId = date.getTime();
				card.setGroupid("a6134faf9a844fe0ae006c7bd1d9a6d5");
				card.setCardid(cardId);
				card.setAmt(new BigDecimal(0.00));
				card.setAvaiabletime(365);
				card.setIsshared("是");
				card.setSource("门店");
				card.setStatus("使用");
				card.setCardname("【"+receivedCouponUser.getName()+receivedCouponUser.getMobile()+"】茉德会员卡");
				card.setCardcode(receivedCouponUser.getMobile());
				card.setComment("来源于首次关注公众号领取优惠券");
				card.setCreateTime(date);
				card.setUserId(userId);
				card.setRemainingNum(1);
				card.setSharingNum(0); //领取优惠券的人不能分享
				card.save();
				jsonObject.put("message", "会员卡套餐已经收入囊中，快去查看吧~");
				// 加入缓存中
				CacheKit.put(DicUtil.CACHE_CARD, userId, card);
				Meal mm = Meal.dao.findMealById(mealId);
				if (null == mm) {
					jsonObject.put("state", "-1");
					jsonObject.put("message", "此套餐分享活动已结束~");
					System.out.println("此套餐分享活动已结束");
				} else {
					Date now = new Date();
					Integer da = new Integer(mm.getMealValidity());
					Date endDate = org.apache.commons.lang3.time.DateUtils.addDays(now, da);
					// 开始绑定套餐
					CardSetMeal setMeal = new CardSetMeal();
					setMeal.setCardId(cardId);
					setMeal.setCardMealId(date.getTime()); // 以时间戳作为主键id
					setMeal.setCardSetMealId(mealId);
					setMeal.setCardMealNumber(1);
					setMeal.setCardMealStarttime(date);
					setMeal.setCardMealEndtime(endDate);
					setMeal.save();
					// 加入缓存中
					CacheKit.put(DicUtil.CACHE_MEAL, mealId + cardId, setMeal);
				}
			} else {
				long exitedCardId = CardOfReceiver.getCardid();
				// 再查询有没有套餐
				CardSetMeal cardSetMeal = CardSetMeal.dao.findMealOfCard(mealId, exitedCardId);
				if (null != cardSetMeal) {
					jsonObject.put("state", "-1");
					jsonObject.put("message", "您已经领过此代金券，不必重复领取~");
					System.out.println("该会员已有此套餐");
				} else {
					System.out.println("该会员已有卡，但无代金券，只绑定代金券");
					Meal mm = Meal.dao.findMealById(mealId);
					if (null == mm) {
						jsonObject.put("state", "-1");
						jsonObject.put("message", "此套餐分享活动已结束~");
						System.out.println("此套餐分享活动已结束");
					} else {
						Date now = new Date();
						Integer da = new Integer(mm.getMealValidity());
						Date endDate = org.apache.commons.lang3.time.DateUtils.addDays(now, da);
						CardSetMeal setMeal = new CardSetMeal();
						setMeal.setCardId(exitedCardId);
						setMeal.setCardMealId(date.getTime());
						setMeal.setCardSetMealId(mealId);
						setMeal.setCardMealNumber(1);
						setMeal.setCardMealStarttime(date);
						setMeal.setCardMealEndtime(endDate);
						setMeal.save();
						// 加入缓存中
						CacheKit.put(DicUtil.CACHE_CARD, exitedCardId, setMeal);
						jsonObject.put("message", "会员代金券已收入囊中~");
					}
				}

			}

		jsonObject.put("officeAddress", "5/445Victoria Ave Chatswood NSW 2067");
		jsonObject.put("officeName", "茉德精品火锅");
		jsonObject.put("sharerName", "茉德精品火锅");
//		jsonObject.put("sharerPhoto", "http://food.3kkk.xyz/carworld_weixin/images/logo.jpg");
		jsonObject.put("userIsFocus", receivedCouponUser.getUserIsfocus());
		return jsonObject;
	}

	
	
}
